import { Module } from 'vuex';
import uuidv1 from 'uuid/v1';
import { cacheObj } from '@/utils';
const cacheCssLabels = cacheObj('css-labels');
const cacheCssItems = cacheObj('css-items');
const main: Module<{ [s: string]: any }, any> = {
  namespaced: true,
  state: {
    labels: cacheCssLabels.get() || [
      {
        name: 'Layout',
      },
    ],
    items: cacheCssItems.get() || [],
  },
  mutations: {
    postCssLabel(state, payload) {
      state.labels.push(payload);
      cacheCssLabels.set(state.labels);
    },
    deleteCssLabel(state, payload) {
      const index = state.labels.findIndex((item: { name: string }) => item.name === payload);
      state.labels.splice(index, 1);
      cacheCssLabels.set(state.labels);
    },

    postCssItem(state, payload: any) {
      if (payload.uuid) {
        const ele = state.items.find((item: { uuid: string }) => item.uuid === payload.uuid);
        if (ele) {
          ele.css = payload.css;
          ele.html = payload.html;
        } else {
          state.items.push(payload);
        }
        cacheCssItems.set(state.items);
      }
    },
    deleteCssItem(state, payload) {
      const index = state.items.findIndex((item: { uuid: string }) => item.uuid === payload);
      state.items.splice(index, 1);
      cacheCssItems.set(state.items);
    },
  },
  actions: {
    postCssItem: ({ commit }, payload) => {
      const uuid = payload.uuid || uuidv1();
      commit('postCssItem', {
        ...payload,
        uuid,
      });
      return Promise.resolve(uuid);
    },
  },
  getters: {
    getCssLabels(state) {
      return state.labels;
    },
    getCssItems: state => (name: string) => {
      return state.items.filter((item: { name: string }) => item.name === name);
    },
    getCssItem: state => (uuid: string) => {
      return state.items.find((item: { uuid: string }) => item.uuid === uuid);
    },
  },
};

export default main;
